package weaver.interfaces.htsc.hrm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.doc.detail.util.DocDownloadCheckUtil;
import sun.misc.BASE64Decoder;
import weaver.conn.RecordSet;
import weaver.docs.docs.ImageFileIdUpdate;
import weaver.general.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

public class OrganizationSynPhoto {

    /***
     *
     * @param url
     */
    public void doHrmSynPhoto(String url,Map<String,String> headMap)
    {
        RecordSet rs = new RecordSet();
        OrganizationSynUtil organizationSynUtil = new OrganizationSynUtil();
        int page = 0;
        int pageSize = 300;
        boolean hasNextPage = true;
        BaseBean bb = new BaseBean();
        while(hasNextPage)
        {
            String urlnew = url+"?page="+page+"&size="+pageSize;
            bb.writeLog("page:"+page);
            String response = organizationSynUtil.sendPost(urlnew,"",headMap);
            if(!"".equals(response))
            {
                JSONArray userArray = JSONArray.parseArray(response);
                for(int i=0;i<userArray.size();i++)
                {
                    JSONObject userJson = userArray.getJSONObject(i);
                    String empCode = Util.null2String(userJson.getString("empCode"));//员工编号

                    try{
                        JSONObject primaryPosition = userJson.getJSONObject("primaryPosition");//主岗信息
                        String deptCode = "" ;
                        if(primaryPosition!=null)
                        {
                            deptCode = primaryPosition.getString("deptCode");
                        }

                        String userState = Util.null2String(userJson.getString("userState"));//用户状态
                        String userId = organizationSynUtil.getUserIdByCode(empCode);  //主账号
                        if("ACTIVE".equalsIgnoreCase(userState))
                        {
                            String photo = Util.null2String(userJson.getString("photo"));
                            synHrmPhoto(empCode,photo,userId,deptCode);
                        }
                    }catch (Exception e){
                        bb.writeLog("OrganizationSyn-e:"+e);
                        e.printStackTrace();
                        rs.writeLog("人员编号"+empCode+"的数据同步失败，data:"+userJson.toJSONString());
                    }
                }
                if(userArray.size()<pageSize)
                {
                    hasNextPage = false;
                }
                page++;
            }else{
                hasNextPage = false;
            }
        }
    }

    /***
     *
     * @param empCode
     * @param photo
     * @param userId
     */
    public void synHrmPhoto(String empCode,String photo,String userId,String deptCode){
        String rootpath = GCONST.getRootPath(); // "/app/ecology";
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        try{
            if(!"".equals(empCode) && empCode !=null)
            {
                String attachfilename = empCode+".jpg";
                String imagefiletype = "image/jpeg" ;
                if("".equals(deptCode))
                {
                    deptCode = "ZZ1000";
                }
                String usericonpath = "filesystem/messager/usericon/"+deptCode+"/"+ empCode;
                String usericonrealpath = rootpath+usericonpath;
                String usericonrealurl = rootpath+usericonpath+"/"+attachfilename ;

                File iconpath = new File(usericonrealpath);
                if (!iconpath.exists())
                {
                    iconpath.mkdirs();
                }
                if(!"".equals(photo) && photo !=null)
                {
                    boolean flag = base64ToImage(photo,usericonrealurl);
                    if(flag)
                    {
                        String resourceimageid = "" ;
                        String sql = " select resourceimageid from hrmresource where id="+userId ;
                        rs.execute(sql);
                        if(rs.next()){
                            resourceimageid = Util.null2String(rs.getString("resourceimageid"));
                        }
                        if(!"".equals(resourceimageid))
                        {
                            String imagefileidold = "" ;
                            sql = " select filerealpath,imagefileid from ImageFile where imagefileid="+resourceimageid;
                            rs.execute(sql);
                            if(rs.next()){
                                imagefileidold = Util.null2String(rs.getString("imagefileid"));
                            }
                            if(!"".equals(imagefileidold))
                            {
                                sql = " update ImageFile set filerealpath='"+usericonrealurl+"' where imagefileid ="+imagefileidold+"" ;
                                rs.writeLog("sql:"+sql);
                                rs.execute(sql);

                                if(!"".equals(userId))
                                {
                                    String fileid = "";
                                    try{
                                        fileid = DocDownloadCheckUtil.checkPermission(imagefileidold,null);
                                    }catch (Exception e){
                                        bb.writeLog("OrganizationSyn-e:"+e);
                                    }
                                    String fileurl = "/htoa/weaver/weaver.file.FileDownload?fileid="+fileid;
                                    sql = " update hrmresource set messagerurl='"+fileurl+"' where workcode='"+empCode+"'" ;
                                    rs.writeLog("sql:"+sql);
                                    rs.execute(sql);
                                }
                            }else{
                                ImageFileIdUpdate im = new ImageFileIdUpdate();
                                int imagefileid = im.getImageFileNewId();
                                rs.writeLog("imagefileid:"+imagefileid);
                                sql= " insert into ImageFile(imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize) "+
                                        " values("+imagefileid+",'"+attachfilename+"','"+imagefiletype+"',1,'"+usericonrealurl+"',0,0,'"+photo.length()+"')";
                                rs.execute(sql);

                                if(!"".equals(userId))
                                {
                                    String fileid = "";
                                    try{
                                        fileid = DocDownloadCheckUtil.checkPermission(imagefileid+"",null);
                                    }catch (Exception e){
                                        bb.writeLog("OrganizationSyn-e:"+e);
                                    }

                                    String fileurl = "/htoa/weaver/weaver.file.FileDownload?fileid="+fileid;
                                    sql = " update hrmresource set resourceimageid="+imagefileid+",messagerurl='"+fileurl+"' where workcode='"+empCode+"'" ;
                                    rs.writeLog("sql:"+sql);
                                    rs.execute(sql);
                                }
                            }
                        }else{
                            ImageFileIdUpdate im = new ImageFileIdUpdate();
                            int imagefileid = im.getImageFileNewId();
                            rs.writeLog("imagefileid:"+imagefileid);
                            rs.writeLog("imagefileid:"+imagefileid);
                            sql= " insert into ImageFile(imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize) "+
                                    " values("+imagefileid+",'"+attachfilename+"','"+imagefiletype+"',1,'"+usericonrealurl+"',0,0,'"+photo.length()+"')";
                            rs.writeLog("sql:"+sql);
                            rs.execute(sql);

                            if(!"".equals(userId))
                            {
                                String fileid = "";
                                try{
                                    fileid = DocDownloadCheckUtil.checkPermission(imagefileid+"",null);
                                }catch (Exception e){
                                    bb.writeLog("OrganizationSyn-e:"+e);
                                }

                                String fileurl = "/htoa/weaver/weaver.file.FileDownload?fileid="+fileid;
                                sql = " update hrmresource set resourceimageid="+imagefileid+",messagerurl='"+fileurl+"' where workcode='"+empCode+"'" ;
                                rs.writeLog("sql:"+sql);
                                rs.execute(sql);
                            }
                        }
                    }else{
                        bb.writeLog(empCode+": no Photo22222");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("OrganizationSyn-e:"+e);
        }
    }

    /**
     * @Descriptionmap 对字节数组字符串进行Base64解码并生成图片
     * @author temdy
     * @Date 2015-01-26
     * @param base64 图片Base64数据
     * @param path 图片路径
     * @return
     */
    public boolean base64ToImage(String base64,String path) {// 对字节数组字符串进行Base64解码并生成图片
        if (base64 == null) { // 图像数据为空
            return false;
        }
        BaseBean bb = new BaseBean();
        bb.writeLog("path:"+path);
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(base64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            bb.writeLog("OrganizationSyn-e:"+e);
            return false;
        }
    }
}
